<template>
  <div class="businessHours_module">
    <el-row>
      <el-col :span="10">
    <el-time-select
      v-model="startTime"
      :start="startPickerOptions.start"
      :step="startPickerOptions.step"
      :end="startPickerOptions.end"
      placeholder="开始时间"
      @change="handleStartTimeChange"
    ></el-time-select>
  </el-col>
  <el-col :span="10">
    <el-time-select class="ml15"
      v-model="endTime"
      :picker-options="endPickerOptions"
      :start="endPickerOptions.start"
      :step="endPickerOptions.step"
      :end="endPickerOptions.end"
      :min-time="endPickerOptions.minTime"
      placeholder="结束时间"
      @change="validateTimeRange"
    ></el-time-select>
  </el-col>
  </el-row>
  </div>
</template>

<script lang="ts">
// 营业时间选择组件
import { defineComponent, PropType, ref, watch } from "vue";
export default defineComponent({
  props: {
    modelValue: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
  },
  emits: ["update:modelValue", "invalid-time-range"],
  setup(props, { emit }) {
    const startTime = ref(props.modelValue[0]);
    const endTime = ref(props.modelValue[1]);
    const startPickerOptions = ref({
      start: "00:00",
      step: "00:30",
      end: "23:30",
    });
    const endPickerOptions = ref({
      start: "00:00",
      step: "00:30",
      end: "23:30",
      minTime: startTime.value,
    });

    const handleStartTimeChange = (value: string) => {
      // 当开始时间改变时，重置结束时间的选择范围
      endPickerOptions.value.minTime = value;
      // 可选：如果新的开始时间大于结束时间，则清空结束时间
      if (endTime.value && value >= endTime.value) {
        endTime.value = "";
      }
    };
    const validateTimeRange = () => {
      if (
        startTime.value &&
        endTime.value &&
        startTime.value >= endTime.value
      ) {
        // 如果开始时间大于或等于结束时间，则发出错误事件
        emit("invalid-time-range", "结束时间必须大于开始时间");
        // 可选：重置结束时间
        endTime.value = "";
      }
    };
    watch([startTime, endTime], (newValues) => {
      emit("update:modelValue", newValues.map((item) => item??""));
    });

    return {
      startTime,
      endTime,
      startPickerOptions,
      endPickerOptions,
      handleStartTimeChange,
      validateTimeRange,
    };
  },
});
</script>
<style scoped></style>
